/* 
https://leetcode.cn/problems/event-emitter/description/

实现一个事件订阅触发机制。
*/

EventEmitter = function () {
  let events = {};

  return {
    subscribe: function (eventName, callback) {
      events[eventName] = events[eventName] ?? []
      events[eventName].push(callback);

      return () => { // 返回一个取消订阅的函数
        events[eventName] = events[eventName].filter(f => f !== callback)
        if (events[eventName].length === 0) delete events[eventName]
      }
    },

    emit: function (eventName, ...args) {
      if !(eventName in events) return []
      return events[eventName].map(f => f(...args))
    }
  }
}

const eventEmit = EventEmitter()
const unSubscribe = eventEmit.subscribe('event1', (a, b) => console.log(a + b))
eventEmit.emit('event1', 1, 2) // 输出 3

